package controller

import (
	"SelectCourse/types"
	"github.com/gin-gonic/gin"
	"net/http"
)

// ScheduleCourse 排课求解器
func ScheduleCourse(c *gin.Context) {
	//获取请求对象
	var request types.ScheduleCourseRequest
	var response types.ScheduleCourseResponse
	response.Data = make(map[string]string)
	if err := c.ShouldBind(&request); err != nil {
		response.Code = types.ParamInvalid
		c.JSON(http.StatusOK, response)
		return
	}
	//排课求解
	binded := make(map[string]*string)
	for key, _ := range request.TeacherCourseRelationShip {
		temp := new(string)
		*temp = key
		used := make(map[string]bool)
		findMatching(temp, binded, used, request.TeacherCourseRelationShip)
	}
	for key, val := range binded {
		response.Data[*val] = key
	}
	response.Code = types.OK
	c.JSON(http.StatusOK, response)
}

// 尝试以 teacher 为起点找到一个更大的匹配
func findMatching(teacher *string, binded map[string]*string, used map[string]bool, relationship map[string][]string) bool {
	if courses, ok := relationship[*teacher]; ok {
		for _, course := range courses {
			if _, ok = used[course]; !ok {
				//fmt.Println("课程", course, "没有被使用过")
				used[course] = true
				if _, ok = binded[course]; !ok || findMatching(binded[course], binded, used, relationship) {
					binded[course] = teacher
					//fmt.Println("课程", course, "和老师", *teacher, "绑定。")
					return true
				}
			}
		}
	}
	return false
}
